import { Image, ScrollView, Textarea, View } from '@tarojs/components';
import { eventCenter, getCurrentInstance } from "@tarojs/runtime";
import classNames from 'classnames';
import { useEffect, useState } from "react";
import data from '../../util/data';
import CustomSocket from '../../util/socket';
import './index.less';
import { createMessage, defaultMessage, Message } from './msg';

let socket = new CustomSocket('wss://shuai.axises.fun')
const robot = require('../../assert/Chat_Icon_Robot.png')
const person = require('../../assert/Chat_Icon_Robot_2.png')
const sendButtonImg = require('../../assert/Chat_Icon_Send.png')

const Chat = ({ showKeyContext = true, isFake = false, tabBarHeight = 60 }) => {
	const [historyMsgList, setHistoryMsgList] = useState<Message[]>([]);
	const [messageContent, setMessageContent] = useState('');
	const [scrollHeight, setScrollHeight] = useState('100vh');
	const [inputBottom, setInputBottom] = useState(0);
	const [listScrollTop, setListScrollTop] = useState(14999);
	const [moveTime, setMoveTime] = useState(0);
	const [isLoading, setIsLoading] = useState(false);
	const [isKeyContext, setIsKeyContext] = useState(showKeyContext);
	const [textAreaHeight, setTextAreaHeight] = useState(40);

	const onReady = () => {
		setHistoryMsgList(historyMsgList => historyMsgList.concat(defaultMessage));
		setIsKeyContext(true);
	}
	const onShow = () => {
		console.log('on chat show...');
		socket.onSocketMessage(updateMessage);
	}

	useEffect(() => {
		const onReadyEventId = getCurrentInstance().router?.onReady
		// 注册一个事件处理函数，当页面Ready时调用onReady函数
		eventCenter.on(onReadyEventId ? onReadyEventId : "空ID", onReady, this)

		const onShowEventId = getCurrentInstance().router?.onShow
		eventCenter.on(onShowEventId ? onShowEventId : "空ID", onShow, this)

		// 如果socket已经连接并打开，直接返回
		if (socket && socket.socketOpen) {
			console.log('socket已经连接并打开')
			return
		}

		// 组件卸载时执行
		return () => {
			// 清空消息列表
			setHistoryMsgList([])
			// 重置加载状态
			setIsLoading(false)
		}
	}, [])

	useEffect(() => {
		setIsKeyContext(!showKeyContext)
		setHistoryMsgList([])
		setIsLoading(false)
	}, [showKeyContext]);


	const updateMessage = (msg: string, imgMsg: string = '') => {
		// 如果消息前缀是“机器人小黑为你服务”，则停止加载
		// if (msg.startsWith('机器人小黑为你服务')) {
		//   setIsLoading(false);
		// }

		// console.log('收到消息：', msg)

		if (msg === '') {
			setIsLoading(false);
			return
		}

		let _contentLength = 0;
		setHistoryMsgList(historyMsgList => {
			if (historyMsgList.length === 0) {
				return historyMsgList
			}
			// 找到最后一个占位消息，替换为正式消息数据
			let prevElement = historyMsgList[historyMsgList.length - 1];

			prevElement.content = prevElement.content + msg;
			_contentLength = prevElement.content.length
			return historyMsgList.slice(0, historyMsgList.length - 1).concat(prevElement)
		});
		setListScrollTop((listScrollTop + (historyMsgList.length + 1) * 1000 + moveTime + _contentLength));
		setIsLoading(false)
	}

	const handleMessageSubmit = () => {
		if (messageContent && messageContent.trim() !== '') {
			let message = createMessage(messageContent.trim(), 'user');
			setHistoryMsgList((prev) => prev.concat(message));

			if (isFake || !data.isOpenGpt) {
				setHistoryMsgList((prev) => prev.concat(createMessage(
					"虚拟管家为您服务，很抱歉，您的问题是" + messageContent + "，管家还在学习中，还不能为你服务...."
				)));
				return
			}

			setIsLoading(true)
			setMoveTime(moveTime + 1);
			const sendMessages = isKeyContext ? historyMsgList.concat(message).map(item => item.content) : [messageContent]

			// 清空输入的消息内容
			setMessageContent('');
			setListScrollTop((listScrollTop + (historyMsgList.length + 1) * 1000 + moveTime));
			// 先添加占位一个空消息，等待服务端响应
			setHistoryMsgList(prevState => prevState.concat(createMessage("")));
			socket.sendChatMessage(sendMessages);
		}
	}

	const handleLineChange = (event) => {
		setTextAreaHeight(event.detail.height)
	}

	const handleKeyboardHeightChange = (e) => {
		setInputBottom(e.detail.height === 0 ? e.detail.height : e.detail.height - tabBarHeight - 25);
	}

	const handleFocus = (e) => {
		setInputBottom(e.detail.height === 0 ? e.detail.height : e.detail.height - tabBarHeight - 25);
	}

	const handleBlur = () => {
		const scrollHeight = '100vh';
		setScrollHeight(scrollHeight);
		setInputBottom(0);
	}

	const handleInput = (e) => {
		setMessageContent(e.detail.value);
	}

	const isRobot = item => {
		return item.type === 'robot';
	}

	const formatMessages = () => {
		return historyMsgList.length > 0 ? historyMsgList : [defaultMessage];
	}

	return (
		<View className='im-page'>
			<View>
				<ScrollView className='im-list' style={{ height: scrollHeight, paddingTop: '10px' }} enableFlex enableBackToTop scrollY scrollTop={listScrollTop}>
					{formatMessages().map((item) => {
						return (
							<View key={item.id} className={classNames({ 'im-list--item__other': isRobot(item), 'im-list--item': true })}>
								<Image className='list-item--avatar' src={isRobot(item) ? robot : person} mode='aspectFit' lazyLoad />
								<View>
									<View className="list-item--name">{isRobot(item) ? "Robot" : "HuanJing"}</View>
									<View className='list-item--content'>{item.content}</View>
								</View>
							</View>
						);
					})}
					<View className='placeholder-box' />
				</ScrollView>
			</View>
			<View className='im-toolbar' style={{ bottom: inputBottom }}>
				<Textarea
					style={{ height: `${textAreaHeight}px` }}
					placeholder={isLoading ? '正在回答中...' : ' 请输入你的问题'}
					placeholderStyle='color: #8b8e94;'
					showConfirmBar={false}
					maxlength={1000}
					disabled={isLoading}
					value={messageContent}
					adjustPosition={false}
					adjust-keyboard-to='bottom'
					confirmType='send'
					onKeyboardHeightChange={handleKeyboardHeightChange}
					onFocus={handleFocus}
					onBlur={handleBlur}
					onInput={handleInput}
					onConfirm={handleMessageSubmit}
					onLineChange={handleLineChange}
				/>
				<Image className="send-button" src={sendButtonImg} onClick={() => handleMessageSubmit()} mode="aspectFit" style={{ width: '30px', height: '30px' }} />
			</View>

		</View>
	);
}

export default Chat
